﻿using System;
using System.Linq.Expressions;
using System.Web.Security;
using SBACN.WebSite.Code;
using SBACN.WebSite.Models;

namespace SBACN.WebSite
{
	public partial class UpdataSn : BasePage
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			this.txt_valid.Attributes.Add("onkeyup", "return DoLogin()");
			this.lblValid.Text = "";
			this.UMsg.Text = "";
			this.OMsg.Text = "";
			this.NMsg.Text = "";
			this.RMsg.Text = "";
		}

		protected void btn_Save_Click(object sender, EventArgs e)
		{

			// 验证码是否相同
			if (this.txt_valid.Text.Trim().ToLower() != Session["Complain"].ToString().ToLower())
			{
				this.lblValid.Text = "验证码输入不正确！";
				return;
			}

			string Name = this.Username.Text;

			Expression<Func<TB_User, bool>> f = (p => (p.UserName == Name ));
			var resultM = DAL.DALHelper.Instance.GetFirstOrDefaultObject<TB_User>(f);

			// 用户是否存在
			if (resultM == null)
			{
				this.UMsg.Text = "用户名错误！";
				return;
			}
			// 旧密码是否相同
			string OsnMD5 = this.Hid_Osn.Value.ToLower();
			string kwO = FormsAuthentication.HashPasswordForStoringInConfigFile(OsnMD5, "MD5").ToLower();
			if (resultM.Password != kwO)
			{
				this.OMsg.Text = "旧密码错误！";
				return;
			}
			// 新密码是否相同
			string NsntMD5 = this.Hid_Nsn.Value.ToLower();
			string N2sntMD5 = this.Hid_RNsn.Value.ToLower();
			string kw = FormsAuthentication.HashPasswordForStoringInConfigFile(string.Empty, "MD5").ToLower();
			if (NsntMD5.Length == 0 || NsntMD5 == kw)
			{
				this.NMsg.Text = "请输入密码。";
				return;
			}

			if (N2sntMD5.Length == 0 || N2sntMD5 == kw)
			{
				this.RMsg.Text = "请输入密码。";
				return;
			}

			if (NsntMD5 != N2sntMD5)
			{
				this.RMsg.Text = "新密码与确认新密码不匹配！";
				return;
			}

			string KeyM = FormsAuthentication.HashPasswordForStoringInConfigFile(NsntMD5, "MD5").ToLower();
			// 写数据库
			resultM.Password = KeyM;
			DAL.DALHelper.Instance.Update<TB_User>(resultM);
			DAL.DALHelper.Instance.SaveChanges();

			ClientScript.RegisterClientScriptBlock(this.GetType(),"AlertMsg","<script> alert('密码修改成功！');window.close(); </script>");
			return;


		}
	}
}